<template>
  <div class="main">
    <div>
      <el-button
        type="success"
        :icon="useRenderIcon('ep:message')"
        :loading="loading"
        @click="openMessageDialog"
      >
        发布站内通知
      </el-button>
    </div>
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="请输入关键字"
          clearable
          class="!w-[150px]"
        />
      </el-form-item>
      <el-form-item label="事件类型" prop="eventType">
        <el-input
          v-model="form.eventType"
          placeholder="请输入事件类型"
          clearable
          class="!w-[150px]"
        />
      </el-form-item>
      <el-form-item label="业务ID" prop="businessId">
        <el-input
          v-model="form.businessId"
          placeholder="请输入业务ID"
          clearable
          class="!w-[150px]"
        />
      </el-form-item>
      <el-form-item label="指定用户" prop="userId">
        <el-select
          ref="userSelectRef"
          v-model="form.userId"
          placeholder="请选择"
          filterable
          remote
          :remote-method="onKeywordInput"
          class="!w-[180px]"
          clearable
          @visible-change="onUserDropdownVisibleChange"
        >
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
          <template v-if="userLoading" #footer>
            <div class="text-center text-xs text-gray-500">
              <span>加载中...</span>
            </div>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="通知类型" prop="type">
        <el-select
          v-model="form.type"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="通知级别" prop="level">
        <el-select
          v-model="form.level"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in levelList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="通知状态" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期范围" prop="time">
        <el-date-picker
          v-model="form.time"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          class="!w-[260px]"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      show-overflow-tooltip
      stripe
      border
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column prop="event" label="事件" width="200" />
      <el-table-column prop="businessId" label="业务ID" width="160" />
      <el-table-column prop="title" label="标题" width="160" />
      <el-table-column prop="channel" label="渠道" width="140" />
      <el-table-column
        prop="type"
        label="类型"
        :formatter="typeFormatter"
        width="160"
      />
      <el-table-column
        prop="level"
        label="级别"
        :formatter="levelFormatter"
        width="160"
      />
      <el-table-column
        prop="status"
        label="状态"
        :formatter="statusFormatter"
        width="100"
      />
      <el-table-column prop="content" label="内容" min-width="200" />
      <el-table-column prop="errorMessage" label="错误信息" min-width="200" />
      <el-table-column prop="sendTime" label="发送时间" width="200" />
      <el-table-column
        prop="updateTime"
        :formatter="val => handleAutoUTC8(val.updateTime)"
        label="更新时间"
        width="200"
      />
      <el-table-column
        prop="createTime"
        :formatter="val => handleAutoUTC8(val.createTime)"
        label="创建时间"
        width="200"
      />
    </el-table>
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <MessageDialog ref="messageDialogRef" @refresh="resetForm(formRef)" />
  </div>
</template>

<script lang="ts" setup>
import { handleAutoUTC8 } from "@/utils/tools";
import { reactive, ref, onMounted, watch, nextTick } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import { getAdminNotificationsList } from "@/api/adminNotificationApi";
import MessageDialog from "./components/MessageDialog.vue";
import {
  userSelectFetcher,
  type UserItem
} from "@/composables/userSelectFetcher";
import { type ElSelect } from "element-plus";
import { useRemotePagedSelect } from "@/composables/useRemotePagedSelect";

// 用户下拉：远程搜索 + 触底加载
const {
  list,
  loading: userLoading,
  onKeywordInput,
  onDropdownScroll
} = useRemotePagedSelect<UserItem>({
  pageSize: 20,
  autoLoad: true,
  debounceMs: 300,
  fetcher: userSelectFetcher
});

const userSelectRef = ref<InstanceType<typeof ElSelect> | null>(null);
let userDropdownWrapEl: HTMLElement | null = null;

function onUserDropdownVisibleChange(visible: boolean) {
  if (visible) {
    nextTick(() => {
      const popperEl = userSelectRef.value?.popperRef as
        | HTMLElement
        | undefined;
      // 在该选择器自己的 popper 里找 wrap
      userDropdownWrapEl =
        popperEl?.querySelector(".el-select-dropdown__wrap") ?? null;
      userDropdownWrapEl?.addEventListener("scroll", onDropdownScroll, {
        passive: true
      });
    });
  } else {
    userDropdownWrapEl?.removeEventListener("scroll", onDropdownScroll);
    userDropdownWrapEl = null;
  }
}

const messageDialogRef = ref();
const openMessageDialog = () => {
  messageDialogRef.value?.open();
};

const formRef = ref();
const loading = ref(false);
const form = reactive({
  time: "",
  type: "",
  userId: "",
  level: "",
  status: "",
  startDate: "",
  endDate: "",
  keyword: "",
  eventType: "",
  businessId: ""
});
const typeList = [
  {
    label: "用户通知",
    value: "USER"
  },
  {
    label: "管理员通知",
    value: "ADMIN"
  },
  {
    label: "系统通知",
    value: "SYSTEM"
  }
];
const levelList = [
  {
    label: "系统通知(最高级别)",
    value: "SYSTEM"
  },
  {
    label: "业务告警(中级别)",
    value: "BUSINESS"
  },
  {
    label: "用户操作(基础级别)",
    value: "USER_OPERATION"
  },
  {
    label: "管理员通知",
    value: "ADMIN"
  },
  {
    label: "文件通知",
    value: "FILE"
  }
];
const statusList = [
  {
    label: "待发送",
    value: "PENDING"
  },
  {
    label: "发送成功",
    value: "SUCCESS"
  },
  {
    label: "发送失败",
    value: "FAILED"
  }
];
const levelFormatter = (row: any) => {
  return levelList.find(item => item.value === row.level)?.label || "--";
};
const statusFormatter = (row: any) => {
  return statusList.find(item => item.value === row.status)?.label || "--";
};
const typeFormatter = (row: any) => {
  return typeList.find(item => item.value === row.type)?.label || "--";
};
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
});
const tableData = ref([]);

watch(
  () => form.time,
  (newVal, oldVal) => {
    if (newVal) {
      form.startDate = newVal[0];
      form.endDate = newVal[1];
    } else {
      form.startDate = "";
      form.endDate = "";
    }
  }
);

async function onSearch() {
  const { time, ...reset } = form;
  const params = {
    page: pagination.currentPage,
    size: pagination.pageSize,
    ...reset
  };
  const { data } = await getAdminNotificationsList(params);
  const { records, total, size, current } = data;
  tableData.value = records;
  pagination.total = total;
  pagination.pageSize = size;
  pagination.currentPage = current;
}
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  form.startDate = "";
  form.endDate = "";
  pagination.currentPage = 1;
  onSearch();
};
onMounted(() => {
  onSearch();
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  gap: 20px;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style>
